package uni.j2ee.forum.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationFilter implements Filter {

	public void doFilter(ServletRequest generalRequest, ServletResponse generalResponse, FilterChain chain) throws IOException, ServletException {
		if ((!(generalRequest instanceof HttpServletRequest))||(!(generalResponse instanceof HttpServletResponse))) {
			throw new IllegalArgumentException("only http requests can be handled");
		}
		final HttpServletRequest request = (HttpServletRequest) generalRequest;
		final HttpServletResponse response = (HttpServletResponse) generalResponse;

		if(request.getServletPath().endsWith("/login.jsp") || request.getServletPath().endsWith("/register.jsp")) {
			//logout action, no permissions needed
			request.getSession().invalidate();
			chain.doFilter(request, response);
			return;
		}
		
		//page that requires permissions
		if(request.getSession(false)==null || request.getSession().getAttribute("user")==null) {
			//no session available
        	response.sendRedirect(request.getContextPath()+"/login.jsf");
        	return;
		}
        //TODO check users permissions
        
        chain.doFilter(request, response);
	}

	public void destroy() {
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
